<?php

namespace app\index\controller;

use think\Controller;

class Base extends Controller
{
    protected $city = '';
    public $account = '';
    protected $categorys = '';
    public function _initialize()
    {
        //获取城市信息
        $res = model('city')->getTree();
        $this->getCity($res);
        $this->getLoginUser();
        //获取首页分类数据
        //显示分类信息
        $categorys = $this->getRecommendCats();
        $this->assign('city', $res);
        $this->assign('citys', $this->city->toArray());
        $this->assign('user', $this->account);
        $this->assign('categorys', $categorys);
        //动态加载配置项
        $this->assign('controller', strtolower(request()->controller()));
        //标题
        $this->assign('title', 'o2o团购网');
    }

    //获取分类信息以及推荐位信息
    public function getRecommendCats()
    {
        $catIds = $sedCatArr = $recomCats = [];
        //获取父级分类
        $cats = model('category')->getNormalRecommendCategoryByParentId(0, 5);
        //遍历父类id
        foreach ($cats as $v) {
            $catIds[] = $v->id;
        }
        //获取二级分类
        $catsPar = model('category')->getNormalCategoryByParentId($catIds);
        //遍历二级分类
        foreach ($catsPar as $cat) {
            $sedCatArr[$cat->parent_id][] = [
                'id' => $cat->id,
                'name' => $cat->name
            ];
        }
        //遍历父级分类
        foreach ($cats as $cat) {
            $recomCats[$cat->id] = [
                'name' => $cat->name,
                'son' => empty($sedCatArr[$cat->id]) ? [] : $sedCatArr[$cat->id]
            ];
        }
        return $recomCats;
    }

    public function getCity($citys)
    {
        $defaultname = '';
        foreach ($citys as $v) {
            if ($v['is_default'] == 1) {
                $defaultname = $v['uname'];
                break;
            }
        }
        $defaultname = $defaultname ? $defaultname : 'nanchang';
        if (session('cityuname', '', 'o2o') && !input('get.city')) {
            $cityuname = session('cityuname', '', 'o2o');
        } else {
            $cityuname = input('get.city', $defaultname, 'trim');
            session('cityuname', $cityuname, 'o2o');
        }
        $this->city = model('City')->where(['uname' => $cityuname])->find();
    }

    public function getLoginUser()
    {
        if (!$this->account) {
            $this->account = session('o2o_user', '', 'o2o');
        }
        return $this->account;
    }
}
